const express = require('express');
const { query } = require('../config/database');
const { authenticateToken, checkRole } = require('../middleware/auth');

const router = express.Router();

// 先校验 token，再判断权限
router.use(authenticateToken);
router.use((req, res, next) => {
  if (!req.user || req.user.role !== 'admin') {
    return res.status(403).json({ message: '权限不足' });
  }
  next();
});

// 获取用户列表（仅管理员）
router.get('/', [authenticateToken, checkRole(['admin'])], async (req, res) => {
  try {
    const { page = 1, limit = 20, search = '' } = req.query;
    const offset = (page - 1) * limit;

    let whereConditions = ['1=1'];
    let params = [];

    if (search) {
      whereConditions.push('(username LIKE ? OR name LIKE ? OR email LIKE ?)');
      params.push(`%${search}%`, `%${search}%`, `%${search}%`);
    }

    const whereClause = whereConditions.join(' AND ');

    const countResult = await query(`SELECT COUNT(*) as total FROM users WHERE ${whereClause}`, params) || [{ total: 0 }];
    const [{ total = 0 } = {}] = countResult;

    const users = await query(
      `SELECT id, username, name, email, role, status, created_at, last_login 
       FROM users 
       WHERE ${whereClause} 
       ORDER BY created_at DESC 
       LIMIT ? OFFSET ?`,
      [...params, parseInt(limit), offset]
    ) || [];

    res.json({
      data: users,
      pagination: {
        page: parseInt(page),
        limit: parseInt(limit),
        total: total,
        pages: Math.ceil(total / limit)
      }
    });

  } catch (error) {
    console.error('获取用户列表错误:', error);
    res.status(500).json({ message: '服务器错误' });
  }
});

// 更新用户状态（仅管理员）
router.put('/:id/status', [authenticateToken, checkRole(['admin'])], async (req, res) => {
  try {
    const { id } = req.params;
    const { status } = req.body;
    if (!status) {
      return res.status(400).json({ message: '缺少参数' });
    }
    const result = await query('UPDATE users SET status = ? WHERE id = ?', [status, id]) || { affectedRows: 0 };
    if (result.affectedRows === 0) {
      return res.status(404).json({ message: '用户不存在' });
    }
    res.json({ message: '用户状态更新成功' });
  } catch (error) {
    console.error('更新用户状态错误:', error);
    res.status(500).json({ message: '服务器错误' });
  }
});

// 更新用户角色（仅管理员）
router.put('/:id/role', [authenticateToken, checkRole(['admin'])], async (req, res) => {
  try {
    const { id } = req.params;
    const { role } = req.body;

    await query(
      'UPDATE users SET role = ? WHERE id = ?',
      [role, id]
    );

    res.json({ message: '用户角色更新成功' });

  } catch (error) {
    console.error('更新用户角色错误:', error);
    res.status(500).json({ message: '服务器错误' });
  }
});

// NEW: GET user holdings for account rebalance page
router.get('/:userId/holdings', (req, res) => {
    const { userId } = req.params;

    const mockClientData = {
      'CUST-113': {
        name: '赵先生',
        id: 'CUST-113',
        riskLevel: '平衡型',
        standardPortfolio: '大类资产轮动',
        holdings: [
          { key: '1', fundName: '广发纳斯达克100ETF', currentWeight: 55, targetWeight: 40 },
          { key: '2', fundName: '易方达沪深300ETF', currentWeight: 30, targetWeight: 40 },
          { key: '3', fundName: '华安黄金ETF', currentWeight: 15, targetWeight: 20 },
        ],
      },
      'CUST-088': {
        name: '孙女士',
        id: 'CUST-088',
        riskLevel: '保守型',
        standardPortfolio: '稳健增长FOF组合',
        holdings: [
          { key: '1', fundName: '华夏成长混合', currentWeight: 20, targetWeight: 25 },
          { key: '2', fundName: '易方达消费行业', currentWeight: 45, targetWeight: 35 },
          { key: '3', fundName: '广发稳健增长', currentWeight: 35, targetWeight: 40 },
        ],
      },
    };

    const client = mockClientData[userId.toUpperCase()];

    if (client) {
        res.json(client);
    } else {
        res.status(404).json({ message: 'Client not found' });
    }
});

// 查单条接口
router.get('/:id', async (req, res) => {
  try {
    const rows = await query('SELECT * FROM users WHERE id = ?', [req.params.id]) || [];
    const [user] = rows;
    if (!user) return res.status(404).json({ message: '用户不存在' });
    res.json([user]);
  } catch (error) {
    console.error('获取用户错误:', error);
    res.status(500).json({ message: '服务器错误' });
  }
});

module.exports = router; 